<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { 
  getReadingSettings, 
  saveReadingSettings, 
  getVoiceSettings, 
  saveVoiceSettings, 
  getDownloadSettings, 
  saveDownloadSettings,
  createTheme,
  deleteTheme,
  applyTheme,
  getCurrentTheme
} from '../services/bookService';

const { proxy } = getCurrentInstance();
// 当前激活的设置选项卡
const activeTab = ref('reading');

// 本地字体
const fontsOption = ref([]);

// 阅读设置
const readingSettings = ref(null);
const currentTheme = ref(null);
const newTheme = ref({
  name: '',
  backgroundColor: '#ffffff',
  color: '#333333',
  fontSize: 18,
  lineHeight: 1.8,
  letterSpacing: 0.5,
  fontFamily: ''
});

// 语音设置
const voiceSettings = ref(null);
const availableVoices = ref([]);

// 下载设置
const downloadSettings = ref(null);
const newFilterKeyword = ref('');

// 选择保存位置
const selectSavePath = async () => {
  try {
    let paths = utools.showOpenDialog({
      title: '选择保存位置',
      buttonLabel: '选择',
      defaultPath: downloadSettings.value.savePath,
      properties: ['openDirectory']
    })
    downloadSettings.value.savePath = paths[0];
    
  } catch (error) {
    proxy.$toast.error('路径选择失败');
  }
};

// 加载字体
const loadFonts = async () => {
  fontsOption.value = await queryLocalFonts();
  fontsOption.value.unshift({
    family: '',
    fullName: '默认字体'
  });
}

// 加载设置
const loadSettings = () => {
  // 加载阅读设置
  readingSettings.value = getReadingSettings();
  currentTheme.value = getCurrentTheme();
  
  // 加载语音设置
  voiceSettings.value = getVoiceSettings();
  
  // 加载下载设置
  console.log(getDownloadSettings());
  
  downloadSettings.value = getDownloadSettings();
  
  // 获取可用的语音列表
  if (window.speechSynthesis) {
    availableVoices.value = window.speechSynthesis.getVoices();
    if (availableVoices.value.length === 0) {
      // 有时需要等待语音列表加载
      window.speechSynthesis.onvoiceschanged = () => {
        availableVoices.value = window.speechSynthesis.getVoices();
      };
    }
  }
};

// 保存阅读设置
const saveReading = () => {
  saveReadingSettings(readingSettings.value);
  proxy.$toast.success('阅读设置已保存');
};

// 保存语音设置
const saveVoice = () => {
  saveVoiceSettings(voiceSettings.value);
  proxy.$toast.success('语音设置已保存');
};

// 保存下载设置
const saveDownload = () => {
  saveDownloadSettings({
    ...downloadSettings.value,
    maxConcurrent: parseInt(downloadSettings.value.maxConcurrent),
    retryCount: parseInt(downloadSettings.value.retryCount)
  });
  proxy.$toast.success('下载设置已保存');
};

// 切换主题
const switchTheme = (themeId) => {
  const theme = applyTheme(themeId);
  if (theme) {
    currentTheme.value = theme;
    readingSettings.value = getReadingSettings();
  }
};

// 添加新主题
const addTheme = () => {
  if (!newTheme.value.name) {
    proxy.$toast.warning('请输入主题名称');
    return;
  }
  
  const theme = createTheme(newTheme.value);
  readingSettings.value = getReadingSettings();
  
  // 重置表单
  newTheme.value = {
    name: '',
    backgroundColor: '#ffffff',
    color: '#333333',
    fontSize: 18,
    lineHeight: 1.8,
    letterSpacing: 0.5,
    fontFamily: ''
  };
};

// 删除主题
const removeTheme = (themeId) => {
  const result = deleteTheme(themeId);
  if (result) {
    readingSettings.value = getReadingSettings();
    proxy.$toast.success('删除成功');
  } else {
    proxy.$toast.error('删除失败');
  }
};

// 添加过滤关键词
const addFilterKeyword = () => {
  if (newFilterKeyword.value && !downloadSettings.value.contentFilter.filterKeywords.includes(newFilterKeyword.value)) {
    downloadSettings.value.contentFilter.filterKeywords.push(newFilterKeyword.value);
    newFilterKeyword.value = '';
  }
};

// 删除过滤关键词
const removeFilterKeyword = (keyword) => {
  const index = downloadSettings.value.contentFilter.filterKeywords.indexOf(keyword);
  if (index !== -1) {
    downloadSettings.value.contentFilter.filterKeywords.splice(index, 1);
  }
};

// 预览主题
const previewTheme = (theme) => {
  return {
    backgroundColor: theme.backgroundColor,
    color: theme.color,
    fontSize: `${theme.fontSize}px`,
    lineHeight: theme.lineHeight,
    letterSpacing: `${theme.letterSpacing}px`,
    fontFamily: theme.fontFamily,
    padding: '10px',
    borderRadius: '4px',
    height: '100px',
    overflow: 'auto'
  };
};

onMounted(() => {
  loadSettings();
  loadFonts();
});
</script>

<template>
  <div class="settings-page">
    <div class="tabs">
      <div 
        class="tab" 
        :class="{ active: activeTab === 'reading' }"
        @click="activeTab = 'reading'"
      >
        阅读设置
      </div>
      <div 
        class="tab" 
        :class="{ active: activeTab === 'voice' }"
        @click="activeTab = 'voice'"
      >
        语音设置
      </div>
      <div 
        class="tab" 
        :class="{ active: activeTab === 'download' }"
        @click="activeTab = 'download'"
      >
        下载设置
      </div>
    </div>
    
    <!-- 阅读设置 -->
    <div v-if="activeTab === 'reading' && readingSettings" class="tab-content">
      <h2>主题设置</h2>
      
      <div class="themes-grid">
        <div 
          v-for="theme in readingSettings.themes" 
          :key="theme.id"
          class="theme-card"
          :class="{ active: readingSettings.currentThemeId === theme.id }"
        >
          <div class="theme-preview" :style="previewTheme(theme)">
            {{ theme.name }}<br>
            这是一段预览文本，用于展示主题效果。
          </div>
          <div class="theme-info">
            <span>{{ theme.name }}</span>
            <div class="theme-actions">
              <button @click="switchTheme(theme.id)" :disabled="readingSettings.currentThemeId === theme.id">
                {{ readingSettings.currentThemeId === theme.id ? '当前主题' : '使用' }}
              </button>
              <button @click="removeTheme(theme.id)" :disabled="readingSettings.currentThemeId === theme.id">
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <h2>创建新主题</h2>
      <div class="new-theme-form">
        <div class="form-group">
          <label>主题名称</label>
          <input v-model="newTheme.name" type="text" placeholder="输入主题名称">
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label>背景颜色</label>
            <input v-model="newTheme.backgroundColor" type="color">
          </div>
          
          <div class="form-group">
            <label>文字颜色</label>
            <input v-model="newTheme.color" type="color">
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label>字体大小 ({{ newTheme.fontSize }}px)</label>
            <input v-model="newTheme.fontSize" type="range" min="12" max="30" step="1">
          </div>
          
          <div class="form-group">
            <label>行高 ({{ newTheme.lineHeight }})</label>
            <input v-model="newTheme.lineHeight" type="range" min="1" max="3" step="0.1">
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label>字间距 ({{ newTheme.letterSpacing }}px)</label>
            <input v-model="newTheme.letterSpacing" type="range" min="0" max="3" step="0.1">
          </div>
          
          <div class="form-group">
            <label>字体</label>
            <select v-model="newTheme.fontFamily">
              <option v-for="item in fontsOption" :value="item.family">{{ item.fullName }}</option>
            </select>
          </div>
        </div>
        
        <div class="theme-preview" :style="previewTheme(newTheme)">
          {{ newTheme.name || '新主题' }}<br>
          这是一段预览文本，用于展示主题效果。
        </div>
        
        <button @click="addTheme" class="btn-primary">创建主题</button>
      </div>
      
      <div class="form-actions">
        <button @click="saveReading" class="btn-primary">保存设置</button>
      </div>
    </div>
    
    <!-- 语音设置 -->
    <div v-if="activeTab === 'voice' && voiceSettings" class="tab-content">
      <div class="form-group">
        <label>语速 ({{ voiceSettings.rate }})</label>
        <input v-model="voiceSettings.rate" type="range" min="0.1" max="10" step="0.1">
      </div>
      
      <div class="form-group">
        <label>音调 ({{ voiceSettings.pitch }})</label>
        <input v-model="voiceSettings.pitch" type="range" min="0.5" max="2" step="0.1">
      </div>
      
      <div class="form-group">
        <label>音量 ({{ voiceSettings.volume }})</label>
        <input v-model="voiceSettings.volume" type="range" min="0" max="1" step="0.1">
      </div>
      
      <div class="form-group" v-if="availableVoices.length > 0">
        <label>语音</label>
        <select v-model="voiceSettings.voiceName">
          <option value="">默认</option>
          <option v-for="voice in availableVoices" :key="voice.name" :value="voice.name">
            {{ voice.name }} ({{ voice.lang }})
          </option>
        </select>
      </div>
      
      <div class="form-actions">
        <button @click="saveVoice" class="btn-primary">保存设置</button>
      </div>
    </div>
    
    <!-- 下载设置 -->
    <div v-if="activeTab === 'download' && downloadSettings" class="tab-content">
      <h2>下载参数</h2>
      
      <div class="form-group">
        <label>保存位置</label>
        <div class="save-path-input">
          <input v-model="downloadSettings.savePath" type="text" placeholder="选择保存位置" readonly>
          <button @click="selectSavePath" class="btn-select">选择</button>
        </div>
      </div>

      <div class="form-group">
        <label>最大并发下载数 ({{ downloadSettings.maxConcurrent  }})</label>
        <input v-model="downloadSettings.maxConcurrent" type="range" min="1" max="10" step="1">
      </div>
      
      <div class="form-group">
        <label>自动重试</label>
        <!-- <input v-model="downloadSettings.autoRetry" type="checkbox"> -->
      </div>
      
      <div class="form-group" v-if="downloadSettings.autoRetry">
        <label>重试次数({{ downloadSettings.retryCount }})</label>
        <input v-model="downloadSettings.retryCount" type="range" min="1" max="10" step="1">
      </div>
      
      <!-- <h2>内容过滤</h2> -->
      
      <!-- <div class="form-group">
        <label>移除广告</label>
        <input v-model="downloadSettings.contentFilter.removeAds" type="checkbox">
      </div> -->
      
      <!-- <div class="form-group">
        <label>清理格式</label>
        <input v-model="downloadSettings.contentFilter.cleanFormatting" type="checkbox">
      </div> -->
      
      <!-- <div class="form-group">
        <label>过滤关键词</label>
        <div class="keyword-input">
          <input v-model="newFilterKeyword" type="text" placeholder="输入关键词">
          <button @click="addFilterKeyword">添加</button>
        </div>
        
        <div class="keywords-list">
          <div 
            v-for="(keyword, index) in downloadSettings.contentFilter.filterKeywords" 
            :key="index"
            class="keyword-tag"
          >
            {{ keyword }}
            <span class="remove-keyword" @click="removeFilterKeyword(keyword)">×</span>
          </div>
        </div>
      </div> -->
      
      <h2>风控设置</h2>
      
      <!-- <div class="form-group">
        <label>启用请求频率限制</label>
        <input v-model="downloadSettings.riskControl.enableRateLimit" type="checkbox">
      </div>
       -->
      <div v-if="downloadSettings?.riskControl?.enableRateLimit">
        <div class="form-group">
          <label>请求间隔 (毫秒)</label>
          <input v-model="downloadSettings.riskControl.requestInterval" type="number">
        </div>
        
        <!-- <div class="form-group">
          <label>每分钟最大请求数</label>
          <input v-model="downloadSettings.riskControl.maxRequestsPerMinute" type="number" min="1" max="100">
        </div> -->
      </div>
      
      <div class="form-actions">
        <button @click="saveDownload" class="btn-primary">保存设置</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #ddd;
  margin-bottom: 20px;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
}

.tab.active {
  border-bottom: 2px solid #4a90e2;
  color: #4a90e2;
}

.tab-content {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-group {
  flex: 1;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.save-path-input {
  display: flex;
  gap: 10px;
  align-items: center;
}

.save-path-input input[type="text"] {
  flex: 1;
  cursor: default;
  background-color: #f5f5f5;
}

.btn-select {
  padding: 6px 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-select:hover {
  background-color: #2980b9;
}

input[type="text"],
input[type="number"],
select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

input[type="range"] {
  width: 100%;
}

input[type="color"] {
  width: 100%;
  height: 40px;
}

.btn-primary {
  background-color: #4a90e2;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #3a80d2;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}

.themes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.theme-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f9f9f9; /* 修改背景颜色以提高对比度 */
}

.theme-card.active {
  border-color: #4a90e2;
  box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.3);
  background-color: #e0f0ff; /* 修改背景颜色以提高对比度 */
}

.theme-info {
  padding: 10px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333; /* 修改字体颜色以提高对比度 */
}

.theme-actions button {
  padding: 3px 8px;
  font-size: 12px;
  border-radius: 3px;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  color: #333; /* 修改字体颜色以提高对比度 */
}

.theme-actions button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: #999; /* 修改字体颜色以提高对比度 */
}

.new-theme-form {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
}

.keyword-input {
  display: flex;
  gap: 10px;
}

.keyword-input input {
  flex: 1;
}

.keywords-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.keyword-tag {
  background-color: #f0f0f0;
  padding: 5px 10px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.remove-keyword {
  cursor: pointer;
  font-weight: bold;
}
</style>